package net.zhengxinyun.performance.service.yearSummaryScore;

import net.zhengxinyun.performance.App.dto.ScoreDTO;
import net.zhengxinyun.performance.Util.DataUtil;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.dto.HeadColums;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.*;
import net.zhengxinyun.performance.mapper.Department.DepartmentEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.CountryIndicatorsEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.CountryUnitScoreEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.TownScoreEntityMapper;
import net.zhengxinyun.performance.mapper.departClass.DepartClassItemMapper;
import net.zhengxinyun.performance.mapper.incentive.IncentiveEntityMapper;
import net.zhengxinyun.performance.mapper.workSupervision.WorkScoreEntityMapper;
import net.zhengxinyun.performance.mapper.yearSummaryScore.YearSummaryScoreEntityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class YearSummaryScoreServiceImp implements YearSummaryScoreService {

    private YearSummaryScoreEntityMapper yearSummaryScoreEntityMapper;
    @Autowired
    private IncentiveEntityMapper incenttiveMapper;
    @Autowired
    private TownScoreEntityMapper townScoreMapper;
    @Autowired
    private CountryIndicatorsEntityMapper cityMapper;

    @Autowired
    private CountryUnitScoreEntityMapper departScoreMapper;

    @Autowired
    private DepartmentEntityMapper departMapper;

    @Autowired
    private DepartClassItemMapper classItemMapper;
    @Autowired
    private WorkScoreEntityMapper workScoreEntityMapper;


    @Autowired
    public YearSummaryScoreServiceImp(YearSummaryScoreEntityMapper yearSummaryScoreEntityMapper) {
        this.yearSummaryScoreEntityMapper = yearSummaryScoreEntityMapper;
    }

    @Override
    public String insert(YearSummaryScoreEntity yearSummaryScore) {
        int i = yearSummaryScoreEntityMapper.insert(yearSummaryScore);
        if (i == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "添加失败,请联系管理员";
        }
        return "添加成功";
    }

    @Override
    public String update(YearSummaryScoreEntity yearSummaryScore) {
        int i = yearSummaryScoreEntityMapper.updateByPrimaryKey(yearSummaryScore);
        if (i == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "修改失败";
        }
        return "修改成功";
    }

    @Override
    public String delete(YearSummaryScoreEntity yearSummaryScore) {
        int temp = yearSummaryScoreEntityMapper.deleteByPrimaryKey(yearSummaryScore.getId());
        if(temp == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "删除失败";
        }
        return "删除成功";
    }

    @Override
    public List<YearSummaryScoreFilter> query(YearSummaryScoreFilter filter) {
        return yearSummaryScoreEntityMapper.query(filter);
    }

    @Override
    public Integer queryForCount(YearSummaryScoreFilter gradePointFilter) {
        return yearSummaryScoreEntityMapper.queryForCount(gradePointFilter);
    }


    /**
     * -------20190909--------------------
     */

    /**
     * 获取指标分数
     * @param datatime
     * @return
     */
    @Override
    public double  getIndexScore(String datatime, DepartmentEntity depart) {
        double finalScore =0;
        double sumWeight =0;
        double sumFinalScore = 0;
        //县对乡镇，
        if("乡镇".equals(depart.getDepartType())) {
            List<TownScoreFilter> townScore = townScoreMapper.queryDepartScore(depart.getDepartcode(), datatime);

             finalScore = townScore.stream().mapToDouble(TownScoreFilter::getDoubleFinalScore).sum();
          /*  if(townScore.size()>1)
            {

                for (TownScoreFilter item : townScore) {
                    if("-".equals(item.getWeight())|| StringUtils.isBlank(item.getWeight()))
                    {
                        continue;
                    }
                    sumWeight= Double.parseDouble(item.getWeight())+sumWeight;
                    sumFinalScore = Double.parseDouble(item.getFinalScore())+sumFinalScore;

                }

                double scoreRate  =  sumFinalScore/sumWeight *100;
                finalScore = Util.formatNumberDouble(2, scoreRate);

            }else if(townScore.size()==1) {
                finalScore = Double.parseDouble(townScore.get(0).getScore());
            }*/

        }else {


            List<CountryIndicatorsFilter> cityList = cityMapper.queryCityScore(depart.getDepartcode(),datatime);

            finalScore = cityList.stream().mapToDouble(CountryIndicatorsFilter::getFinalScoreNotNull).sum();

        /*    if(cityList.size()>=1){

                for (CountryIndicatorsFilter item : cityList) {
                    if("-".equals(item.getWeight())||item.getWeight()==0)
                    {
                        continue;
                    }


                    sumWeight= item.getWeight()+sumWeight;
                    sumFinalScore = item.getFinalScore()+sumFinalScore;

                }
                double scoreRate  =  sumFinalScore/sumWeight *100;
                finalScore = Util.formatNumberDouble(2, scoreRate);
            }else if(cityList.size()==1){
                finalScore = cityList.get(0).getScore();
            }*/


        }



        return finalScore;
    }

    //正向激励得分
    @Override
    public String getIncetiveScore(String datetime,String departCode) {

        String socre="0";
        double sumScore=0;
        IncentiveFilter incentive = new IncentiveFilter();
        incentive.setDepartCode(departCode);
        incentive.setAudit("1");
        incentive.setDateTime(datetime.substring(0,4));
        List<IncentiveFilter> list = incenttiveMapper.query(incentive);
        for (IncentiveFilter item : list) {

            sumScore= Double.parseDouble(item.getPoint())+sumScore;

        }

        socre=sumScore+"";
        return socre;
    }

    // 县直单位
    @Override
    public List<CountryUnitScoreEntity> getUintScore(String datetime,DepartmentEntity depart) {

        String year = datetime.substring(0,4);
        List<CountryUnitScoreEntity> list = departScoreMapper.selectDepartScore(datetime, depart.getDepartcode(), year);
       /* for (CountryUnitScoreEntity item : list) {

        }*/


        return list;
    }

    //工作督查
    @Override
    public String getWorkScore(String datetime,String departCode) {
        WorkScoreFilter filter = new WorkScoreFilter();
        filter.setDateTime(datetime);
        filter.setDepartCode(departCode);
        List<WorkScoreFilter> query = workScoreEntityMapper.queryScore(filter);
        double sumWroks = query.stream().mapToDouble(WorkScoreFilter::getDouleFinalScore  ).sum();

        return sumWroks+"";
    }

    //获取单位总得分
    @Override
    public HashMap<String,Object> getDepartScore(List<DepartClassHead> headslist,String datetime,String departCode,String type,String clasid) {

       return  getDeptScore(headslist,datetime,departCode,type,clasid);
    }


    private HashMap<String,Object> getDeptScore(List<DepartClassHead> headslist,String datetime,String departCode,String departType,String clasid)
    {


        HashMap<String,Object> tableMap = new LinkedHashMap<>();

        List<Map<String,Object>> dataList  = new ArrayList<>();
        //获取相应的单位
        List<DepartmentEntity> departs = departMapper.selectForDepartment(departCode,departType,clasid);
        departs= departs.stream().filter(departmentFilter -> !departmentFilter.getDepartment().equals("超级管理员")).collect(Collectors.toList());
        Map<String,String> headMap = new LinkedHashMap<>();
        int i =1;
        String cell ="cell";
        for (DepartClassHead head : headslist) {
            headMap.put(head.getWeightName(),cell+i);
            i++;
        }


        // app得分lisi
        List<ScoreDTO> scorelist = new ArrayList<>();

        for (DepartmentEntity depart : departs) {

            Map<String,Object> itemMap = new HashMap<>();
            itemMap.put("departName",depart.getDepartAddr());
            itemMap.put("datetime",datetime);
            double indexScore= getIndexScore(datetime,depart);
            itemMap.put(headMap.get("指标得分"),indexScore+"");
            String jiliScore = getIncetiveScore(datetime, depart.getDepartcode());
            itemMap.put(headMap.get("正向激励"),jiliScore);
            List<CountryUnitScoreEntity> uintScores = getUintScore(datetime, depart); // 县直单位得分
            for (CountryUnitScoreEntity unitScore : uintScores) {
                itemMap.put(headMap.get(unitScore.getIndexName()),unitScore.getScore());
            }
            dataList.add(itemMap);
            itemMap.put("totalScore",0);
            itemMap.put("departCode",depart.getDepartcode());
            itemMap.put("departType",depart.getDepartType());
            //单位分类不为空的
            if(StringUtils.isNotBlank(depart.getDepartClas()))
            {
                Map<String, String> departScore = uintScores.stream().collect(Collectors.toMap(o -> o.getIndexName(), o -> o.getScore() == null ? "0" : o.getScore()));
                List<DepartClassItem> weights = classItemMapper.queryDepartWeight(depart.getDepartClas(), datetime.substring(0,4));
                for (DepartClassItem weight : weights) {
                    System.out.println(weight.getWeightName() + weight.getWeight());
                    if("指标得分".equals(weight.getWeightName()))
                    {
                        double score = indexScore*weight.getWeight()/100;

                        weight.setScore(DataUtil.formatNumberDouble(2,score));
                    }
                    if("正向激励".equals(weight.getWeightName()))
                    {
                        double score = Double.parseDouble(jiliScore)*weight.getWeight()/100;
                        weight.setScore(DataUtil.formatNumberDouble(2,score));
                    }
                    if(departScore.containsKey(weight.getWeightName()))
                    {
                        double score =Double.parseDouble(departScore.get(weight.getWeightName().trim()))*weight.getWeight()/100;
                        weight.setScore(DataUtil.formatNumberDouble(2,score));
                    }

                }
                double totalScore=0;
              /*  for (DepartClassItem item : weights) {
                    totalScore = totalScore+(item.getWeight()*item.getScore()/100 );
                }*/
              totalScore = weights.stream().mapToDouble(DepartClassItem::getScore).sum();
                itemMap.put("totalScore",Util.formatNumber(2,totalScore));
                scorelist.add( new ScoreDTO(totalScore,depart.getDepartcode(),datetime,null,depart.getDepartAddr()) );

            }else {
                scorelist.add( new ScoreDTO(0,depart.getDepartcode(),datetime,null,depart.getDepartAddr()) );

            }


        }

        dataList.size();

        List<HeadColums>  tableHead = new ArrayList<>();
        // Map<String, Object> map1 = dataMap.get(0);

        tableHead.add(new HeadColums("单位名称","departName"));
        tableHead.add(new HeadColums("考核月份","datetime"));
        tableHead.add(new HeadColums("总分","totalScore"));
        for(Map.Entry<String,String> entry:headMap.entrySet())
        {
            tableHead.add(new HeadColums(entry.getKey(),entry.getValue()));

        }
        tableMap.put("tableData",dataList);
        tableMap.put("tableHead",tableHead);
        tableMap.put("scoreData",scorelist);// 总分
        return  tableMap;
    }




}
